import 'package:flutter/material.dart';
import 'package:delivery_application/model/order_model.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class MyOrder extends StatefulWidget {
  const MyOrder({super.key});

  @override
  State<MyOrder> createState() => _MyOrderState();
}

class _MyOrderState extends State<MyOrder> {
  List<Order> orders = [];
  bool isEditing = false;
  Set<int> selectedOrders = {};

  @override
  void initState() {
    super.initState();
    _loadOrders();
  }

  Future<void> _loadOrders() async {
    final prefs = await SharedPreferences.getInstance();
    final orderStrings = prefs.getStringList('orders') ?? [];
    setState(() {
      orders = orderStrings
          .map((str) => Order.fromJson(jsonDecode(str)))
          .toList()
          .reversed
          .toList();
      selectedOrders.clear();
    });
  }

  void _toggleSelectAll() {
    setState(() {
      if (selectedOrders.length == orders.length) {
        // 如果全部选中，则取消全选
        selectedOrders.clear();
      } else {
        // 否则全选
        selectedOrders = Set.from(List.generate(orders.length, (index) => index));
      }
    });
  }

  Future<void> _deleteSelectedOrders() async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除${selectedOrders.length}个选中的订单吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text(
              '删除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    if (confirm != true) return;

    // 获取当前SharedPreferences中的订单数据
    final prefs = await SharedPreferences.getInstance();
    final orderStrings = prefs.getStringList('orders') ?? [];
    final allOrdersFromStore = orderStrings
        .map((str) => Order.fromJson(jsonDecode(str)))
        .toList();
    
    // 获取要删除的订单的orderNumber和createTime
    final List<String> orderIdsToDelete = [];
    for (final index in selectedOrders) {
      final order = orders[index];
      orderIdsToDelete.add('${order.orderNumber}-${order.createTime.toString()}');
    }
    
    // 创建要保留的订单列表
    final List<String> remainingOrderStrings = [];
    final List<Order> remainingOrders = [];
    
    // 检查每个订单是否应该被保留
    for (int i = 0; i < allOrdersFromStore.length; i++) {
      final order = allOrdersFromStore[i];
      final orderId = '${order.orderNumber}-${order.createTime.toString()}';
      if (!orderIdsToDelete.contains(orderId)) {
        remainingOrderStrings.add(orderStrings[i]);
        remainingOrders.add(order);
      }
    }
    
    // 更新SharedPreferences
    await prefs.setStringList('orders', remainingOrderStrings);
    
    // 更新UI
    setState(() {
      orders = remainingOrders.reversed.toList();
      selectedOrders.clear();
      isEditing = false;
    });

    // 显示删除成功提示
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('已删除${orderIdsToDelete.length}个订单')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff00AEEE),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          iconTheme: const IconThemeData(color: Colors.white),
          title: const Text(
            '历史订单',
            style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          actions: [
            if (orders.isNotEmpty)
              TextButton(
                onPressed: () {
                  setState(() {
                    if (isEditing) {
                      selectedOrders.clear();
                    }
                    isEditing = !isEditing;
                  });
                },
                child: Text(
                  isEditing ? '完成' : '编辑',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
          ],
        ),
        body: orders.isEmpty
            ? const Center(
                child: Text(
                  '暂无订单记录',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
              )
            : Column(
                children: [
                  if (isEditing)
                    Container(
                      color: Colors.white.withOpacity(0.1),
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      child: Row(
                        children: [
                          Checkbox(
                            value: selectedOrders.length == orders.length,
                            onChanged: (value) => _toggleSelectAll(),
                            checkColor: Colors.white,
                            fillColor: MaterialStateProperty.all(Color(0xff00AEEE)),
                          ),
                          Text(
                            '全选',
                            style: TextStyle(color: Colors.white),
                          ),
                          Spacer(),
                          Text(
                            '已选择 ${selectedOrders.length} 项',
                            style: TextStyle(color: Colors.white),
                          ),
                        ],
                      ),
                    ),
                  Expanded(
                    child: ListView.builder(
                      itemCount: orders.length,
                      itemBuilder: (context, index) {
                        final order = orders[index];
                        return Card(
                          margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                          child: ListTile(
                            leading: isEditing
                                ? Checkbox(
                                    value: selectedOrders.contains(index),
                                    onChanged: (bool? value) {
                                      setState(() {
                                        if (value == true) {
                                          selectedOrders.add(index);
                                        } else {
                                          selectedOrders.remove(index);
                                        }
                                      });
                                    },
                                    activeColor: Color(0xff00AEEE),
                                  )
                                : null,
                            title: Text(
                              '订单号: ${order.orderNumber}',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('地址: ${order.address}'),
                                Text(
                                  '创建时间: ${order.createTime.toString().split('.')[0]}',
                                  style: TextStyle(color: Colors.grey),
                                ),
                              ],
                            ),
                            onTap: isEditing ? () {
                              setState(() {
                                if (selectedOrders.contains(index)) {
                                  selectedOrders.remove(index);
                                } else {
                                  selectedOrders.add(index);
                                }
                              });
                            } : null,
                          ),
                        );
                      },
                    ),
                  ),
                  if (isEditing)
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: ElevatedButton(
                        onPressed: selectedOrders.isEmpty ? null : _deleteSelectedOrders,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          minimumSize: const Size(double.infinity, 50),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25),
                          ),
                        ),
                        child: Text(
                          selectedOrders.isEmpty ? '请选择要删除的订单' : '删除选中的${selectedOrders.length}个订单',
                          style: TextStyle(
                            color: selectedOrders.isEmpty ? Colors.grey : Colors.black,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
      ),
    );
  }
}
